package com.binguo.wxapi.controller;


import com.binguo.common.constants.ProductConstants;
import com.binguo.common.enums.ProductStorageType;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.paymodel.ThreadManager;
import com.binguo.common.util.FileDownloader;
import com.binguo.common.util.PriceUtil;
import com.binguo.model.api.vo.MinorCategoryVO;
import com.binguo.model.api.vo.ProductVO;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.repository.ProductRepository;
import com.binguo.service.ProductService;
import com.binguo.service.ShopProductMsgService;
import com.binguo.service.ShopService;
import com.binguo.wxapi.baidu.BaiduEasyDLUtil;
import com.binguo.wxapi.baidu.BaiduRecUtil;
import com.binguo.wxapi.form.*;
import com.binguo.wxapi.result.Result;
import com.binguo.wxapi.result.ResultGenerator;

import com.binguo.wxapi.service.BowlService;
import com.binguo.wxapi.util.ChineseCharacterUtil;

import com.binguo.wxapi.vo.ProductImgVO;

import com.binguo.wxapi.vo.ProductInfoVO;
import com.binguo.yprecapi.YpRecService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.binguo.common.constants.ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_OFFLINE;
import static com.binguo.common.constants.ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_OFFLINE_PURE;
import static com.binguo.common.constants.ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_ONLINE;
import static com.binguo.common.exception.ErrorCode.CUSTOMER_NOT_EXIST;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@Api(tags = "小程序: 菜品上传")
@RestController
@RequestMapping
public class WxProductController {

    private static Logger logger = LoggerFactory.getLogger(WxProductController.class);

    private static String ipAddress = System.getenv("ipAddress");

    @Resource
    ProductService productService;

    @Resource
    BaiduEasyDLUtil baiduEasyDLUtil;


    @Resource
    private BaiduRecUtil baiduRecUtil;
    @Resource
    private BowlService bowlService;

    @Resource
    private ShopService shopService;

    @Resource
    private YpRecService ypRecService;


    @Resource
    private ShopProductMsgService shopProductMsgService;

    @Resource
    private ShopBranchBaiduIdMapper shopBranchBaiduIdMapper;

    @Resource
    private LogShopBaiduImgDelMapper logShopBaiduImgDelMapper;

    @PostMapping(value = "/api/wxapp/updateProductSubDb", produces = APPLICATION_JSON_VALUE)
    public Result updateProductSubDb(@RequestBody ProductSubDbForm form){
        addProductSubDb(form.getShopId(), form.getBranchId(), form.getProductIdList());

        productService.addShopProductVersion(form.getShopId());
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping(value = "/api/wxapp/delProductSubDb", produces = APPLICATION_JSON_VALUE)
    public Result delProductSubDb(@RequestBody ProductSubDbUpdateForm form){
        Product productDb = productService.getProductById(form.getProductId());
        delProductSubDb(productDb.getShopid(), productDb.getStoreid(), form.getProductId());

        Condition productSubCondition = new Condition(ProductSub.class);
        productSubCondition.or().andEqualTo("shopId", productDb.getShopid())
                .andEqualTo("branchId", productDb.getStoreid())
        ;
        productService.addShopProductVersion(form.getShopId());

        List<ProductVO> productVOList = productService.findCurProductList(productDb.getShopid(), productDb.getStoreid());

        if (productVOList != null && productVOList.size() > 0) {
            return ResultGenerator.genSuccessResult(productVOList);
        }else {
            return ResultGenerator.genSuccessResult(null);
        }
    }

    @PostMapping(value = "/api/wxapp/getMeshProductList", produces = APPLICATION_JSON_VALUE)
    public Result getMeshProductList(@RequestBody ShopForm form){

        List<Branch> branchList = shopService.getBranchList(form.getShopId());

        if (branchList != null && branchList.size() > 0) {
            Integer branchId = branchList.get(0).getBranchId();

            if (form.getBranchId() != null && form.getBranchId() > 0) {
                branchId = form.getBranchId();
            }
            Map<String, Object> result
                    = shopService.getMeshProductList(branchId);

            if (result != null) {
                int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                if (hour >= 10 && hour < 15) {//中餐
                    result.put("meshTime", 2);
                } else if (hour >= 15) {//晚餐
                    result.put("meshTime", 3);
                } else {//早餐
                    result.put("meshTime", 1);
                }
            } else {
                result = new HashMap<>();
            }


            result.put("branchList", branchList);
            result.put("branchId", branchId);
            return ResultGenerator.genSuccessResult(result);
        } else {
            throw new ServiceException("暂无预订");
        }

    }

    @PostMapping(value = "/api/wxapp/getBranchList", produces = APPLICATION_JSON_VALUE)
    public Result getBranchList(@RequestBody ShopForm form){

        List<Branch> branchList = shopService.getBranchList(form.getShopId());

        return ResultGenerator.genSuccessResult(branchList);
    }

    @PostMapping(value = "/api/wxapp/productimg/create", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加菜品图片", notes = "通过CreateCardForm")
    public Result create(@RequestBody @Valid CreateProductForm form) {
        logger.info("添加菜品图片:{}", form.toString());
        Product product = productService.getProductById(form.getProductId());

        //{productId=6824, productUrl='http://img.binguoai.com/tmp_77f49e4da717232b44165edd25239c4a.jpg'}
//        boolean result = baiduEasyDLUtil.detection(form.getProductUrl(), product.getShopid(),
//                form.getProductId(), product.getStoreid());

        boolean result = bowlService.checkBowlLocation(product.getShopid(), product.getId(), product.getStoreid(), form.getProductUrl());

        if (result) {
            return ResultGenerator.genSuccessResult();
        } else {

            return ResultGenerator.genFailResult("添加失败");
        }
    }

    @PostMapping("/api/wxapp/productimg/addImg")
    public Result upload3(@RequestParam("file") MultipartFile file,
                          @RequestParam("shopId")Integer shopId,
                          @RequestParam("productId")Integer productId,
                          HttpServletResponse response) {
        Product product = productService.getProductById(productId);

        String filepath = bowlService.wxapiFilepath + "/wxapiimg/" + shopId;

        File tempFile = new File(filepath);

        if (!tempFile.exists()) {
            tempFile.mkdir();
        }

        filepath += "/productimg";

        tempFile = new File(filepath);

        if (!tempFile.exists()) {
            tempFile.mkdir();
        }

        filepath += "/" + System.currentTimeMillis() + ".png";
        File dest = new File(filepath);

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String cont_sign = null;
        try {
            Shop shop = shopService.findShopById(shopId);


            String filepathUrl = filepath.replace(bowlService.wxapiFilepath, "http://" + ipAddress);
            if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_ONLINE) {
                //判断是否本地识别
                ypRecService.addImg(filepathUrl, product.getStoreid(), productId, bowlService.localRecIp);
            }else if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_OFFLINE_PURE) {
                //判断是否本地识别
                ypRecService.addImg(filepathUrl, product.getStoreid(),  productId,bowlService.productYPRecIpAddress + ":5001");
            }else if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_OFFLINE) {
                //判断是否本地识别
                LogProductImg logProductImg = new LogProductImg();
                logProductImg.setImgCutNetUrl(filepathUrl);
                logProductImg.setCutImg(filepath);
                logProductImg.setProductId(productId);
                logProductImg.setShopId(shopId);
                logProductImg.setSourceImg(filepath);
                logProductImg.setContSign(cont_sign);
                logProductImg.setCreateTime(new Date());
                logProductImg.setBaiduDeleted(0);
                logProductImg.setFromWxUpload(1);
                logProductImg.setBranchId(product.getStoreid());

                shopProductMsgService.addInsertProductImgMessage(logProductImg);
            }else {
                cont_sign = baiduRecUtil.addImg(shopId, product.getStoreid(), filepath, shopId + "_" + productId);
            }


            LogProductImgFromUser logProductImgFromUser = new LogProductImgFromUser();
            logProductImgFromUser.setContSign(cont_sign);
            logProductImgFromUser.setCreateTime(new Date());
            logProductImgFromUser.setCutImg(filepath);
            logProductImgFromUser.setSourceImg(filepath);
            logProductImgFromUser.setProductId(productId);
            logProductImgFromUser.setShopId(product.getShopid());
            logProductImgFromUser.setFromCorrect(1);
            logProductImgFromUser.setBaiduDeleted(0);
            logProductImgFromUser.setImgCutNetUrl(filepathUrl);
            logProductImgFromUser.setImgSrcNetUrl(filepathUrl);
            logProductImgFromUser.setSubDb(0);
            logProductImgFromUser.setBranchId(product.getStoreid());

            logProductImgFromUserMapper.insert(logProductImgFromUser);

        } catch (Exception e) {
            logger.error("添加菜品图片失败:{}", e);
            e.printStackTrace();
            return ResultGenerator.genFailResult("添加菜品图片失败");
        }


        return ResultGenerator.genSuccessResult();
    }

    @PostMapping(value = "/api/wxapp/meshproductimg/create", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加在线订餐菜品图片", notes = "通过CreateCardForm")
    public Result meshProductImgCreate(@RequestBody @Valid CreateProductForm form) {

        logger.info("添加在线订餐菜品图片:{}", form.toString());
        Product product = productService.getProductById(form.getProductId());

        productService.addMeshProductImg(product.getShopid(), product.getId(), form.getProductUrl(), product.getStoreid());

        return ResultGenerator.genSuccessResult();
    }

    @PostMapping(value = "/api/wxapp/product/create", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加菜品", notes = "")
    public Result createProduct(@RequestBody @Valid AddProductForm form) {
        if (!PriceUtil.isPrice(form.getProductPrice())) {
            return ResultGenerator.genFailResult("金额参数不正确");
        }

        int productNameCount = productService.countProductNameByShopAndBranchPos(form.getProductName()
                , form.getShopId(), form.getBranchId()
        );

        if (productNameCount > 0) {
            return ResultGenerator.genFailResult("菜名有重复");
        }

        int count = productService.countProductByShop(form.getShopId());

        String value = org.apache.commons.lang3.StringUtils.leftPad(count + "", 4, "0");

        long time = System.currentTimeMillis();

        long price = new Double(new Double(form.getProductPrice()) * 100).longValue();

        Product product = new Product();
        product.setShopid(form.getShopId());
        product.setCreated(new Date());
        product.setName(form.getProductName());
        product.setPrice(price);
        product.setDeleted(false);
        product.setMinorcategoryid(form.getProductCategoryID());
        product.setVipprice(price);
        product.setStatus(new Byte("1"));
        product.setSearchcode(value + time);
        product.setProductType(1);
        product.setStoreid(form.getBranchId());
        product.setDescription(form.getDescription());

        Integer productId = productService.addProduct(product);

        productService.addShopProductVersion(form.getShopId());

        if (StringUtils.hasText(form.getYpProductId())) {
            if (form.getYpProductId().contains(",")) {
                String[] ypProductIdList = form.getYpProductId().split(",");
                for (String ypProductId: ypProductIdList) {
                    productService.refYpProduct(product.getShopid(), product.getId(),
                            Integer.valueOf(ypProductId), form.getProductName());
                }
            }else {
                if (!form.getYpProductId().equals("0")) {
                    productService.refYpProduct(product.getShopid(), product.getId(),
                            Integer.valueOf(form.getYpProductId()), form.getProductName());
                }
            }

        }



        return ResultGenerator.genSuccessResult(productId);
    }


    @PostMapping(value = "/api/wxapp/meshproduct/create", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加在线订餐菜品", notes = "")
    public Result createMeshProduct(@RequestBody @Valid AddProductForm form) {
        if (!PriceUtil.isPrice(form.getProductPrice())) {
            return ResultGenerator.genFailResult("金额参数不正确");
        }

        int productNameCount = productService.countProductNameByShopAndBranch(form.getProductName()
                , form.getShopId(), form.getBranchId()
        );

        if (productNameCount > 0) {
            return ResultGenerator.genFailResult("菜名有重复");
        }

        int count = productService.countProductByShop(form.getShopId());

        String value = org.apache.commons.lang3.StringUtils.leftPad(count + "", 4, "0");

        long time = System.currentTimeMillis();

        long price = new Double(new Double(form.getProductPrice()) * 100).longValue();

        Product product = new Product();
        product.setShopid(form.getShopId());
        product.setCreated(new Date());
        product.setName(form.getProductName());
        product.setPrice(price);
        product.setDeleted(false);
        product.setMinorcategoryid(form.getProductCategoryID());
        product.setVipprice(price);
        product.setStatus(new Byte("1"));
        product.setSearchcode(value + time);
        product.setProductType(2);
        product.setStoreid(form.getBranchId());
        product.setDescription(form.getDescription());

        productService.addProduct(product);

        ProductInventory productInventory = new ProductInventory();
        productInventory.setBreakfastGeneralSum(form.getBreakfastGeneralSum());
        productInventory.setBraekfastSum(form.getBreakfastSum());
        if (form.getBreakfastGeneralSum().intValue() != ProductStorageType.Limited.getCode()) {
            productInventory.setBraekfastSum(0);
        }
        productInventory.setLunchGeneralSum(form.getLunchGeneralSum());
        productInventory.setLunchSum(form.getLunchSum());
        if (form.getLunchGeneralSum().intValue() != ProductStorageType.Limited.getCode()) {
            productInventory.setLunchSum(0);
        }
        productInventory.setDinnerGeneralSum(form.getDinnerGeneralSum());
        productInventory.setDinnerSum(form.getDinnerSum());
        if (form.getDinnerGeneralSum().intValue() != ProductStorageType.Limited.getCode()) {
            productInventory.setDinnerSum(0);
        }
        productInventory.setProductId(product.getId());
        productInventory.setShopId(form.getShopId());
        productInventory.setStandard(form.getStandard());

        productService.addProductInventory(productInventory);


        return ResultGenerator.genSuccessResult();
    }



    @PostMapping(value = "/api/wxapp/product/update", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改菜品", notes = "")
    public Result updateProduct(@RequestBody @Valid UpdateProductForm form) {
        if (!PriceUtil.isPrice(form.getProductPrice())) {
            return ResultGenerator.genFailResult("金额参数不正确");
        }
        Product product = productService.getProductById(form.getProductId());

        int productNameCount = productService.countProductNameByShopAndBranchBeforeUpdatePos(form.getProductName()
                , product.getShopid(), product.getStoreid(), product.getId()
        );

        if (productNameCount > 0) {
            return ResultGenerator.genFailResult("菜名有重复");
        }


        long price = new Double(new Double(form.getProductPrice()) * 100).longValue();

        Product temp = new Product();
        temp.setId(product.getId());
        temp.setName(form.getProductName());
        temp.setMinorcategoryid(form.getProductCategoryID());
        temp.setPrice(price);
        temp.setDescription(form.getDescription());

        productService.updateProductSelective(temp);

        productService.addShopProductVersion(product.getShopid());

        if (StringUtils.hasText(form.getYpProductId())) {
            productService.delRefYpProduct(product.getShopid(), product.getId());
            if (form.getYpProductId().contains(",")) {
                String[] ypProductIdList = form.getYpProductId().split(",");
                for (String ypProductId: ypProductIdList) {
                    productService.refYpProduct(product.getShopid(), product.getId(),
                            Integer.valueOf(ypProductId),product.getName());
                }
            }else {
                if (!form.getYpProductId().equals("0")) {
                    productService.refYpProduct(product.getShopid(), product.getId(),
                            Integer.valueOf(form.getYpProductId()),product.getName());
                }
            }

        }

        return ResultGenerator.genSuccessResult();
    }



    @PostMapping(value = "/api/wxapp/product/getYpProduct", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取云澎菜品列表", notes = "")
    public Result getYpProductList(@RequestBody ShopForm shopForm) {

        return ResultGenerator.genSuccessResult(productService.getYpProductList(shopForm.getShopId()));
    }


    @PostMapping(value = "/api/wxapp/meshproduct/update", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改在线订餐菜品", notes = "")
    public Result updateMeshProduct(@RequestBody @Valid UpdateProductForm form) {
        if (!PriceUtil.isPrice(form.getProductPrice())) {
            return ResultGenerator.genFailResult("金额参数不正确");
        }

        Product product = productService.getProductById(form.getProductId());

        int productNameCount = productService.countProductNameByShopAndBranchBeforeUpdate(form.getProductName()
                , product.getShopid(), product.getStoreid(), product.getId()
        );

        if (productNameCount > 0) {
            return ResultGenerator.genFailResult("菜名有重复");
        }

        long price = new Double(new Double(form.getProductPrice()) * 100).longValue();

        Product temp = new Product();
        temp.setId(product.getId());
        temp.setName(form.getProductName());
        temp.setMinorcategoryid(form.getProductCategoryID());
        temp.setPrice(price);
        temp.setDescription(form.getDescription());

        productService.updateProductSelective(temp);


        ProductInventory productInventory = productService.getMeshProductById(form.getProductId());

        ProductInventory tempProductInventory = new ProductInventory();

        tempProductInventory.setId(productInventory.getId());
        tempProductInventory.setBreakfastGeneralSum(form.getBreakfastGeneralSum());
        tempProductInventory.setBraekfastSum(form.getBreakfastSum());
        if (form.getBreakfastGeneralSum().intValue() != ProductStorageType.Limited.getCode()) {
            tempProductInventory.setBraekfastSum(0);
        }
        tempProductInventory.setLunchGeneralSum(form.getLunchGeneralSum());
        tempProductInventory.setLunchSum(form.getLunchSum());
        if (form.getLunchGeneralSum().intValue() != ProductStorageType.Limited.getCode()) {
            tempProductInventory.setLunchSum(0);
        }
        tempProductInventory.setDinnerGeneralSum(form.getDinnerGeneralSum());
        tempProductInventory.setDinnerSum(form.getDinnerSum());
        if (form.getDinnerGeneralSum().intValue() != ProductStorageType.Limited.getCode()) {
            tempProductInventory.setDinnerSum(0);
        }
        tempProductInventory.setStandard(form.getStandard());

        productService.updateProductInventory(tempProductInventory);

        return ResultGenerator.genSuccessResult();
    }

    @PostMapping(value = "/api/wxapp/product/getProductCategoryList", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品分类", notes = "")
    public Result getProductCategoryList(@RequestBody @Valid GetProductCategoryForm form) {
        List<MinorCategoryVO> vos = productService.findCategory(form.getShopID());
        return ResultGenerator.genSuccessResult(vos);
    }



    @PostMapping(value = "/api/wxapp/meshproduct/status", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改在线订餐菜品状态", notes = "")
    public Result updateProductStatus(@RequestBody @Valid UpdateProductStatusForm form) {
        Product product = productService.getProductById(form.getProductId());

        if (product != null) {
            productService.changeProductStatus(form.getProductId(), form.getStatus());
        }else {
            return ResultGenerator.genFailResult("参数错误");
        }

        List<ProductVO> list = productService.findMeshProducts(product.getShopid(), Optional.empty(),
                Optional.empty(), product.getStoreid());

        return ResultGenerator.genSuccessResult(list);

    }

    @PostMapping(value = "/api/wxapp/meshproduct/delete", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除在线订餐菜品", notes = "")
    public Result deleteMeshProduct(@RequestBody @Valid DeleteProductForm form) {
        Product product = productService.getProductById(form.getProductId());

        product.setDeleted(true);
        product.setStatus(new Byte("2"));

        productService.updateProduct(product);

        List<ProductVO> list = productService.findMeshProducts(product.getShopid(),
                Optional.empty(), Optional.empty(), product.getStoreid());


        return ResultGenerator.genSuccessResult(list);
    }

    @GetMapping(value = "/api/wxapp/product/deleteTemp", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除菜品", notes = "")
    public Result deleteProductTemp(@RequestParam Integer productId) {
        Condition condition = new Condition(LogProductImgFromUser.class);
        condition.or().andEqualTo("shopId", "164")
                .andEqualTo("baiduDeleted", "0")
        ;
        List<LogProductImg> logProductImgFromUserList= logProductImgMapper.selectByCondition(condition);

        if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
            Set<Integer> productIdList = new HashSet<>();
            for (LogProductImg logProductImgFromUser : logProductImgFromUserList) {
                productIdList.add(logProductImgFromUser.getProductId());
            }
            Condition productCondition = new Condition(Product.class);
            productCondition.or().andIn("id", productIdList).andEqualTo("deleted", false);
            List<Product> productList = productRepository.findByCondition(productCondition);
            if (productIdList != null && productList.size() > 0) {
                List<Integer> integerList = new ArrayList<>();
                for (Product product : productList) {
                    if (productIdList.contains(product.getId())) {
                        integerList.add(product.getId());
                    }
                }

                productIdList.removeAll(integerList);
                if (productIdList.size() > 0) {
                    for (Integer pId : productIdList) {
                        doDeleteProductTemp(pId);
                    }
                }
            }
        }

        return null;

//        List<ProductVO> list = productService.findProducts(product.getShopid(), Optional.empty(), Optional.empty());

//        return ResultGenerator.genSuccessResult(list);
    }

    @PostMapping(value = "/api/wxapp/product/delete", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除菜品", notes = "")
    public Result deleteProduct(@RequestBody @Valid DeleteProductForm form) {
        Product product = productService.getProductById(form.getProductId());
        Result result = doDeleteProduct(product);

        Product targetProduct = productService.getShopProductRefProductId(product.getId(), product.getShopid());

        if (targetProduct != null) {
            doDeleteProduct(targetProduct);
        }
        productService.addShopProductVersion(product.getShopid());

        return result;

//        List<ProductVO> list = productService.findProducts(product.getShopid(), Optional.empty(), Optional.empty());

//        return ResultGenerator.genSuccessResult(list);
    }


    @PostMapping(value = "/api/wxapp/product/info", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品", notes = "")
    public Result getProduct(@RequestBody @Valid DeleteProductForm form) {
        Product product = productService.getProductById(form.getProductId());

        ProductInfoVO productInfoVO = new ProductInfoVO();
        productInfoVO.setProductName(product.getName());
        productInfoVO.setProductPrice(product.getPrice().toString());
        productInfoVO.setProductCategoryId(product.getMinorcategoryid());

        List<Integer> productYpId = productService.getYpProduct(product.getId(), product.getShopid(), product.getStoreid());
        if (productYpId != null && productYpId.size() > 0) {
            String productIdListStr = org.apache.commons.lang3.StringUtils.join(productYpId.toArray(), ",");
            productInfoVO.setProductYpId(productIdListStr);
        }


        return ResultGenerator.genSuccessResult(productInfoVO);
    }


    @PostMapping(value = "/api/wxapp/meshproduct/info", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取在线订餐菜品", notes = "")
    public Result meshproductInfo(@RequestBody @Valid DeleteProductForm form) {
        Product product = productService.getProductById(form.getProductId());

        ProductInventory productInventory = productService.getMeshProductById(form.getProductId());

        ProductInfoVO productInfoVO = new ProductInfoVO();
        productInfoVO.setProductName(product.getName());
        productInfoVO.setProductPrice(product.getPrice().toString());
        productInfoVO.setProductCategoryId(product.getMinorcategoryid());

        productInfoVO.setBreakfastGeneralSum(productInventory.getBreakfastGeneralSum());
        productInfoVO.setLunchGeneralSum(productInventory.getLunchGeneralSum());
        productInfoVO.setDinnerGeneralSum(productInventory.getDinnerGeneralSum());
        productInfoVO.setBreakfastSum(productInventory.getBraekfastSum());
        productInfoVO.setLunchSum(productInventory.getLunchSum());
        productInfoVO.setDinnerSum(productInventory.getDinnerSum());
        productInfoVO.setStandard(productInventory.getStandard());

        return ResultGenerator.genSuccessResult(productInfoVO);
    }


    @GetMapping(value = "/api/wxapp/product/list", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品列表", notes = "通过商户id,一级类目id,二级类目id")
    public Result getProducts(@ApiParam("商户id") @RequestParam @NotNull Integer shopId,
                              @RequestParam Integer branchId,
                              @ApiParam("一级类目id") @RequestParam Optional<Integer> majorCategoryId,
                              @ApiParam("二级类目id") @RequestParam Optional<Integer> minorCategoryId) {
        if (branchId == null) {
            List<ProductVO> list = productService.findProductsForWX(shopId, majorCategoryId, minorCategoryId);
            Collections.sort(list, Comparator.comparing(ProductVO::getPrice));
            return ResultGenerator.genSuccessResult(list);
        }else {
            List<ProductVO> list = productService.findBranchProductsForWX(shopId, majorCategoryId,
                    minorCategoryId, branchId);

            if (list == null || list.size() == 0) {
                list = productService.findProductsForWX(shopId, majorCategoryId, minorCategoryId);
            }
            Collections.sort(list, Comparator.comparing(ProductVO::getPrice));
            return ResultGenerator.genSuccessResult(list);
        }
    }

    @GetMapping(value = "/api/wxapp/meshProduct/list", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取在线订餐菜品列表", notes = "通过商户id,一级类目id,二级类目id")
    public Result findMeshProducts(@ApiParam("商户id") @RequestParam @NotNull Integer shopId,
                                   @RequestParam @NotNull Integer branchId,
                              @ApiParam("一级类目id") @RequestParam Optional<Integer> majorCategoryId,
                              @ApiParam("二级类目id") @RequestParam Optional<Integer> minorCategoryId) {
        List<ProductVO> list = productService.findMeshProducts(shopId, majorCategoryId, minorCategoryId, branchId);
        return ResultGenerator.genSuccessResult(list);
    }



    @PostMapping(value = "/api/wxapp/productimg/list", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取菜品图片列表", notes = "通过FaceListForm")
    public Result faceList(@RequestBody @Valid ProductImgListForm form) {
        List<LogProductImg> logProductImgList = productService.getProductImgByProductId(form.getProductId());
        List<ProductImgVO> productImgVOList = new ArrayList<>();
        if (logProductImgList != null && logProductImgList.size() > 0) {
            for (LogProductImg logProductImg : logProductImgList) {
                ProductImgVO productImgVO = new ProductImgVO();
                if (logProductImg.getSourceImg() != null && logProductImg.getSourceImg().startsWith("http")) {
                    productImgVO.setImgUrl(logProductImg.getSourceImg());
                }else{
                    if (logProductImg.getImgCutNetUrl() != null &&  logProductImg.getImgCutNetUrl().startsWith("http")) {
                        productImgVO.setImgUrl(logProductImg.getImgCutNetUrl());
                    }else {
                        continue;
                    }
                }
                productImgVO.setProductImgId(logProductImg.getId());

                productImgVOList.add(productImgVO);
            }
        }
        return ResultGenerator.genSuccessResult(productImgVOList);
    }



    @PostMapping(value = "/api/wxapp/productimg/correctDel", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除菜品纠正图片", notes = "")
    public Result delWxImg(@RequestBody @Valid DelProductImgForm form) {
        LogProductImgFromUser logProductImgFromUser = productService.getProductImgFromCorrectById(form.getProductImgId());

        if (logProductImgFromUser == null) {
            return ResultGenerator.genFailResult("fail");
        }

        if (StringUtils.hasText(logProductImgFromUser.getContSign())) {
            if(!baiduRecUtil.delImg(logProductImgFromUser.getContSign(),
                    logProductImgFromUser.getShopId(), logProductImgFromUser.getBranchId())){
                return ResultGenerator.genFailResult("fail");
            }

            productService.delProductImgFromUser(form.getProductImgId());

            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genFailResult("fail");
        }

    }

    @PostMapping(value = "/api/wxapp/productimg/del", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除菜品图片", notes = "通过DelProductImgForm")
    public Result delFace(@RequestBody @Valid DelProductImgForm form) {
        logger.info("delFace: {}" , form);
        Product product = productService.getProductById(form.getProductId());

        if (product == null) {
            throw new ServiceException("产品不存在");
        }
        List<LogProductImg> logProductImgList = productService.getProductImgByProductId(form.getProductId());
        if (logProductImgList.size() == 0) {
            throw new ServiceException("菜品图片数量必须大于一张");
        }

        LogProductImg temp = productService.getProductImgById(form.getProductImgId());

        if (StringUtils.hasText(temp.getContSign())) {
            if(!baiduRecUtil.delImg(temp.getContSign(), temp.getShopId(), temp.getBranchId())){
                LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                logShopBaiduImgDel.setLogId(temp.getId());
                logShopBaiduImgDel.setStatus(0);

                logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
            }
        }

        String imgCutUrl = productService.delProductImg(form.getProductImgId());

        Shop shop = shopService.findShopById(product.getShopid());

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_ONLINE) {
            ypRecService.delImg(imgCutUrl, product.getStoreid(), bowlService.localRecIp);
        }

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_OFFLINE_PURE) {
            ypRecService.delImg(imgCutUrl, product.getStoreid(), bowlService.localRecIp);
        }

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == ProductConstants.SHOP_PRODUCT_REC_TYPE_YP_OFFLINE) {
            shopProductMsgService.addDeleteProductImgMessage(temp);
        }

        logger.info("WxFaceController.delProductImg");
        logProductImgList = productService.getProductImgByProductId(form.getProductId());

        List<ProductImgVO> productImgVOList = new ArrayList<>();
        if (logProductImgList != null && logProductImgList.size() > 0) {
            for (LogProductImg logProductImg : logProductImgList) {
                ProductImgVO productImgVO = new ProductImgVO();

                if (logProductImg.getSourceImg() != null && logProductImg.getSourceImg().startsWith("http")) {
                    productImgVO.setImgUrl(logProductImg.getSourceImg());
                }else{
                    if (logProductImg.getImgCutNetUrl() != null &&  logProductImg.getImgCutNetUrl().startsWith("http")) {
                        productImgVO.setImgUrl(logProductImg.getImgCutNetUrl());
                    }else {
                        continue;
                    }
                }

                productImgVO.setProductImgId(logProductImg.getId());

                productImgVOList.add(productImgVO);
            }
        }

        return ResultGenerator.genSuccessResult(productImgVOList);
    }


    @PostMapping(value = "/api/wxapp/meshproductimg/del", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除菜品图片", notes = "通过DelProductImgForm")
    public Result meshproductimgDel(@RequestBody @Valid DelProductImgForm form) {
        logger.info("meshproductimg: {}" , form);

        Product product = productService.getProductById(form.getProductId());

        if (product == null) {
            throw new ServiceException("产品不存在");
        }
        List<LogProductImg> logProductImgList = productService.getProductImgByProductId(form.getProductId());
        if (logProductImgList.size() == 1) {
            throw new ServiceException("菜品图片数量必须大于一张");
        }

//        LogProductImg temp = productService.getProductImgById(form.getProductImgId());


        String imgCutUrl = productService.delProductImg(form.getProductImgId());

        Shop shop = shopService.findShopById(product.getShopid());

        logger.info("WxFaceController.delProductImg");
        logProductImgList = productService.getProductImgByProductId(form.getProductId());

        List<ProductImgVO> productImgVOList = new ArrayList<>();
        if (logProductImgList != null && logProductImgList.size() > 0) {
            for (LogProductImg logProductImg : logProductImgList) {
                ProductImgVO productImgVO = new ProductImgVO();
                if (logProductImg.getSourceImg() != null && logProductImg.getSourceImg().startsWith("http")) {
                    productImgVO.setImgUrl(logProductImg.getSourceImg());
                }else{
                    if (logProductImg.getImgCutNetUrl() != null &&  logProductImg.getImgCutNetUrl().startsWith("http")) {
                        productImgVO.setImgUrl(logProductImg.getImgCutNetUrl());
                    }else {
                        continue;
                    }
                }

                productImgVO.setProductImgId(logProductImg.getId());

                productImgVOList.add(productImgVO);
            }
        }

        return ResultGenerator.genSuccessResult(productImgVOList);
    }



    @PostMapping(value = "/api/wxapp/product/addtarget", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加菜品图片", notes = "通过CreateCardForm")
    public Result addTargetShop(@RequestBody @Valid AddShopProductForm form) {
        logger.info(form.toString());
        addProduct(form.getSourceShopId(), form.getTargetShopId());

        return ResultGenerator.genSuccessResult();
    }


    @Resource
    private ProductRepository productRepository;

    @Resource
    private BranchMapper branchMapper;
    @Resource
    private LogProductImgMapper logProductImgMapper;
    @Resource
    private LogProductImgFromUserMapper logProductImgFromUserMapper;
    @Resource
    private ProductSubMapper productSubMapper;
    @Resource
    private ShopBaiduUrlCurMapper shopBaiduUrlCurMapper;


    public void addProduct(Integer sourceShopId, Integer targetShopId){
        Condition productCondition = new Condition(Product.class);
        productCondition.or().andEqualTo("shopid", sourceShopId)
                .andEqualTo("deleted", false)
        ;
        List<Product> sourceProductList = productRepository.findByCondition(productCondition);


        if (sourceProductList != null && sourceProductList.size() > 0) {
            Condition targetProductCondition = new Condition(Product.class);
            targetProductCondition.or().andEqualTo("shopid", targetShopId)
                            .andEqualTo("deleted", false)
            ;

            List<Product> targetProductList = productRepository.findByCondition(targetProductCondition);

            Map<String, Product> targetProductMap = null;
            if (targetProductList != null && targetProductList.size() > 0) {
                targetProductMap = targetProductList.stream().collect(Collectors.toMap(Product::getSearchcode, p -> p));
            }

            Condition branchCondition = new Condition(Branch.class);
            branchCondition.or().andEqualTo("shopId", targetShopId);
            List<Branch> branchList = branchMapper.selectByCondition(branchCondition);
            Integer branchId = null;
            if (branchList != null && branchList.size() > 0) {
                branchId = branchList.get(0).getBranchId();
            }

            for (Product product : sourceProductList) {
                if (targetProductMap != null && targetProductMap.containsKey(product.getSearchcode())) {

                    Product targetProduct = targetProductMap.get(product.getSearchcode());
                    if (StringUtils.isEmpty(targetProduct.getProductpic())) {
                        if (StringUtils.hasText(product.getProductpic())) {
                            boolean result = baiduEasyDLUtil.detection(product.getProductpic(), targetShopId,
                                    targetProduct.getId(), branchId);

                            if (result) {
                                logger.info("error:{}", targetProduct.getId());
                            }
                        }else {
                            Condition logProductImgCondition = new Condition(LogProductImg.class);
                            logProductImgCondition.or().andEqualTo("shopId", product.getShopid())
                                    .andEqualTo("productId", product.getId())
                                    .andEqualTo("baiduDeleted", 0);
                            List<LogProductImg> logProductImgList =
                                    logProductImgMapper.selectByCondition(logProductImgCondition);

                            if (logProductImgList != null && logProductImgList.size() > 0) {
                                String picUrl = logProductImgList.get(0).getSourceImg();

                                boolean result = baiduEasyDLUtil.detection(picUrl, targetShopId,
                                        targetProduct.getId(), branchId);

                                if (result) {
                                    logger.info("error:{}", targetProduct.getId());
                                }
                            }
                        }
                    }else {
                        Condition logProductImgCondition = new Condition(LogProductImg.class);
                        logProductImgCondition.or().andEqualTo("shopId", targetProduct.getShopid())
                                .andEqualTo("productId", targetProduct.getId())
                                .andEqualTo("baiduDeleted", 0);
                        List<LogProductImg> logProductImgList =
                                logProductImgMapper.selectByCondition(logProductImgCondition);

                        if (logProductImgList != null && logProductImgList.size() > 0) {
                            continue;
                        }else {
                            Condition sourceLogProductImgCondition = new Condition(LogProductImg.class);
                            sourceLogProductImgCondition.or().andEqualTo("shopId", product.getShopid())
                                    .andEqualTo("productId", product.getId())
                                    .andEqualTo("baiduDeleted", 0);
                            List<LogProductImg> sourceLogProductImgList =
                                    logProductImgMapper.selectByCondition(sourceLogProductImgCondition);

                            if (sourceLogProductImgList != null && sourceLogProductImgList.size() > 0) {
                                String picUrl = sourceLogProductImgList.get(0).getSourceImg();
                                boolean result = baiduEasyDLUtil.detection(picUrl, targetShopId,
                                        targetProduct.getId(), branchId);

                                if (result) {
                                    logger.info("error:{}", targetProduct.getId());
                                }
                            }
                        }
                    }



                    continue;
                }
                Product tempProduct = new Product();
                BeanUtils.copyProperties(product, tempProduct);

                tempProduct.setShopid(targetShopId);
                tempProduct.setStoreid(branchId);
                tempProduct.setId(null);
                tempProduct.setCreated(new Date());
                tempProduct.setUpdated(new Date());
                productRepository.save(tempProduct);

                if (StringUtils.hasText(product.getProductpic())) {
                    boolean result = baiduEasyDLUtil.detection(product.getProductpic(), targetShopId,
                            tempProduct.getId(), branchId);
                }
            }
        }
    }


    private void doDeleteProductTemp(Integer productId) {

        List<LogProductImg> logProductImgList = productService.getAllProductImgList(productId);
        if (logProductImgList != null) {
            List<Integer> idList = new ArrayList<>();
            logProductImgList.stream().forEach(p -> {
                if(baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId())){
                    idList.add(p.getId());
                }else {
                    LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                    logShopBaiduImgDel.setLogId(p.getId());
                    logShopBaiduImgDel.setImgType(1);
                    logShopBaiduImgDel.setStatus(0);

                    logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                }
            });

            if (idList.size() > 0) {
                productService.deleteProductImgList(idList);
            }
        }

        List<LogProductImgFromUser> logProductImgFromUserList = productService.getProductImgFromUserList(productId);
        if (logProductImgFromUserList != null) {
            List<Integer> idList = new ArrayList<>();
            logProductImgFromUserList.stream().forEach(p -> {
                boolean deleted ;
                if (p.getSubDb() == null || p.getSubDb() == 0) {
                    deleted = baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId());
                }else {
                    deleted = baiduRecUtil.delImgCurList(p.getContSign(), p.getShopId(), p.getBranchId(), p.getBaiduAppId());
//                    deleted = baiduRecUtil.delImgCur(p.getContSign(), p.getShopId(), p.getBranchId());
                }

                if(deleted){
                    idList.add(p.getId());
                }else {
                    LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                    logShopBaiduImgDel.setLogId(p.getId());
                    logShopBaiduImgDel.setImgType(2);
                    logShopBaiduImgDel.setStatus(0);

                    logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                }
            });

            if (idList.size() > 0) {
                productService.deleteProductImgFromUserList(idList);
            }
        }

        productService.delProductImgList(productId);


    }


    private void doDeleteProductSubDb(){

    }

    private Result doDeleteProduct(Product product) {


        product.setDeleted(true);
        product.setStatus(new Byte("2"));
        product.setUpdated(new Date());

        productService.updateProduct(product);

        Shop shop = shopService.findShopById(product.getShopid());

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == SHOP_PRODUCT_REC_TYPE_YP_ONLINE) {
            ypRecService.delProductAndFiles(product.getId(), product.getStoreid(), bowlService.localRecIp);
        }

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == SHOP_PRODUCT_REC_TYPE_YP_OFFLINE_PURE) {
            ypRecService.delProductAndFiles(product.getId(), product.getStoreid(), bowlService.localRecIp);
        }

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == SHOP_PRODUCT_REC_TYPE_YP_OFFLINE) {
            shopProductMsgService.addDeleteProductMessage(product);
        }


        List<LogProductImg> logProductImgList = productService.getAllProductImgList(product.getId());
        if (logProductImgList != null) {
            List<Integer> idList = new ArrayList<>();
            logProductImgList.stream().forEach(p -> {
                boolean deleted ;
                if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
                    deleted = true;
//                    deleted = ypRecService.delImg(p.getImgCutNetUrl(), shop.getId(), bowlService.localRecIp);
                }else{
                    deleted = baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId());
                }

                if(deleted){
                    idList.add(p.getId());
                }else {
                    LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                    logShopBaiduImgDel.setLogId(p.getId());
                    logShopBaiduImgDel.setImgType(1);
                    logShopBaiduImgDel.setStatus(0);

                    logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                }
            });

            if (idList.size() > 0) {
                productService.deleteProductImgList(idList);
            }
        }

        List<LogProductImgFromUser> logProductImgFromUserList = productService.getProductImgFromUserList(product.getId());
        if (logProductImgFromUserList != null) {
            List<Integer> idList = new ArrayList<>();
            logProductImgFromUserList.stream().forEach(p -> {
                boolean deleted ;

                if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
                    deleted = true;
//                    deleted = ypRecService.delImg(p.getImgCutNetUrl(), shop.getId(), bowlService.localRecIp);
                }else{
                    if (p.getSubDb() == null || p.getSubDb() == 0) {
                        deleted = baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId());
                    }else {
                        deleted = baiduRecUtil.delImgCurList(p.getContSign(), p.getShopId(), p.getBranchId(), p.getBaiduAppId());
                    }
                }

                if(deleted){
                    idList.add(p.getId());
                }else {
                    LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                    logShopBaiduImgDel.setLogId(p.getId());
                    logShopBaiduImgDel.setImgType(2);
                    logShopBaiduImgDel.setStatus(0);

                    logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                }
            });

            if (idList.size() > 0) {
                productService.deleteProductImgFromUserList(idList);
            }
        }

        productService.delProductImgList(product.getId());

        productService.delProductYpRef(product.getId(), product.getShopid());

        if (product.getStoreid() == null) {
            List<ProductVO> list = productService.findProductsForWX(product.getShopid(),
                    Optional.empty(), Optional.empty());
            Collections.sort(list, Comparator.comparing(ProductVO::getPrice));
            return ResultGenerator.genSuccessResult(list);
        }else {
            List<ProductVO> list = productService.findBranchProductsForWX(product.getShopid(), Optional.empty(),
                    Optional.empty(), product.getStoreid());

            if (list == null || list.size() == 0) {
                list = productService.findProductsForWX(product.getShopid(), Optional.empty(), Optional.empty());
            }
            Collections.sort(list, Comparator.comparing(ProductVO::getPrice));
            return ResultGenerator.genSuccessResult(list);
        }
    }

    @GetMapping(value = "/api/wxapp/product/getlistByFirstName", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "按首字母获取菜品列表", notes = "通过商户id,一级类目id,二级类目id")
    public Result getProductByFirstName(@ApiParam("商户id") @RequestParam @NotNull Integer shopId,
                                        @RequestParam Integer branchId,
                                        @ApiParam("一级类目id") @RequestParam Optional<Integer> majorCategoryId,
                                        @ApiParam("二级类目id") @RequestParam Optional<Integer> minorCategoryId) {
        if (branchId == null) {
            List<ProductVO> list = productService.findProductsForWX(shopId, majorCategoryId, minorCategoryId);
            if (list != null && list.size() > 0) {
                Collections.sort(list, Comparator.comparing(ProductVO::getPrice));
                return ResultGenerator.genSuccessResult(list);
            }else {
                return ResultGenerator.genSuccessResult(list);
            }
        }else {
            List<ProductVO> list = productService.findBranchProductsForWX(shopId, majorCategoryId,
                    minorCategoryId, branchId);

            if (list != null && list.size() > 0) {
                Collections.sort(list, Comparator.comparing(ProductVO::getPrice));
                //按照首字母排序
                List<ProductListSortByChinaForm> pc = new ArrayList<>();
                for(int i = 0; i < list.size(); i++){

                    //获取首字母
                    String x = ChineseCharacterUtil.convertHanzi2Pinyin(list.get(i).getName().trim(),true).substring(0,1);
                    ProductListSortByChinaForm productListSortByChinaForm = new ProductListSortByChinaForm();
                    productListSortByChinaForm.setName(x.toUpperCase());
                    productListSortByChinaForm.setList(list.get(i));
                    pc.add(productListSortByChinaForm);
                }
                int flag = 0;
                //排序
                Collections.sort(pc,Comparator.comparing(ProductListSortByChinaForm::getName));
                List<ProductListSortByChinaListForm>  backList = new ArrayList<>();
                for(int i = 0; i < pc.size(); i++){
                    if(i>0){
                        //拿当前字段和所有字段进行比较
                        if(pc.get(i).getName().equals(pc.get(i-1).getName())){
                            continue;
                        }else{
                            List<ProductListSortByChinaForm> pb = new ArrayList<>();
                            ProductListSortByChinaListForm px = new ProductListSortByChinaListForm();
                            for(int j = flag; j < i; j++){
                                pb.add(pc.get(j));

                            }
                            px.setP(pb);
                            px.setName(pc.get(i-1).getName());
                            backList.add(px);
                            flag = i;
                        }

                    }
                    //封装对象
                }
                List<ProductListSortByChinaForm> pb = new ArrayList<>();
                ProductListSortByChinaListForm px = new ProductListSortByChinaListForm();
                for(int i = flag; i < pc.size(); i++){
                    pb.add(pc.get(i));
                    px.setP(pb);
                    px.setName(pc.get(i).getName());
                    //封装对象
                }
                backList.add(px);
                return ResultGenerator.genSuccessResult(backList);
            }else {
                return ResultGenerator.genSuccessResult(list);
            }
        }
    }



    @GetMapping(value = "/api/wxapp/product/getSubDbProductList", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "按首字母获取当日小库菜品列表", notes = "通过商户id,一级类目id,二级类目id")
    public Result getSubProductByFirstName(@ApiParam("商户id") @RequestParam @NotNull Integer shopId,
                                        @RequestParam Integer branchId,
                                        @ApiParam("一级类目id") @RequestParam Optional<Integer> majorCategoryId,
                                        @ApiParam("二级类目id") @RequestParam Optional<Integer> minorCategoryId) {

        List<ProductVO> productVOList = productService.findCurProductList(shopId, branchId);
        if (productVOList != null) {
            return ResultGenerator.genSuccessResult(productVOList);
        }else {
            return ResultGenerator.genSuccessResult(null);
        }
    }


    @GetMapping(value = "/api/wxapp/product/addDbProductToNew", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "添加旧商品图片到新菜品", notes = "")
    public Result erase(@RequestParam @NotNull Integer oldProductId, @RequestParam @NotNull Integer newProductId) {

        List<LogProductImgFromUser> logProductImgFromUserList = productService.getImgListByProductId(oldProductId);

        if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
            Product product = productService.getProductById(newProductId);
            for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUserList) {
                if (logProductImgFromUser.getImgCutNetUrl() != null) {
                    addImg(logProductImgFromUser.getShopId(), newProductId, logProductImgFromUser.getImgCutNetUrl(), product.getStoreid());
                }
            }
        }
        return ResultGenerator.genSuccessResult(null);

    }



    public void delProductSubDb(Integer shopId, Integer branchId, Integer productId){
        Shop shop = shopService.findShopById(shopId);

        if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
            ThreadManager.executorService.execute(() ->
                    ypRecService.delProduct(productId, branchId, bowlService.localRecIp)
            );

        }else{
            delImg(shopId, productId, branchId);
        }

        Condition condition = new Condition(ProductSub.class);
        condition.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
        ;

        productSubMapper.deleteByCondition(condition);
    }

    public void addProductSubDb(Integer shopId, Integer branchId, List<Integer> productIdList){
        Condition condition = new Condition(ShopBaiduUrlCur.class);
        condition.or().andEqualTo("shopId", shopId)
                .andEqualTo("branchId", branchId)
        ;

        List<ShopBaiduUrlCur> shopBaiduUrlCurList = shopBaiduUrlCurMapper.selectByCondition(condition);

        if (shopBaiduUrlCurList != null && shopBaiduUrlCurList.size() > 0) {
            logger.info("shop baidu url config: {}", shopBaiduUrlCurList.get(0).getApiKey());
        }else {
            throw new ServiceException("未开通今日菜品库");
        }

        Condition productSubCondition = new Condition(ProductSub.class);
        productSubCondition.or().andEqualTo("shopId", shopId)
                .andEqualTo("branchId", branchId)
        ;

        List<ProductSub> dbProductSubList = productSubMapper.selectByCondition(productSubCondition);

        /*if (dbProductSubList != null && dbProductSubList.size() > 0) {
            //已有产品，筛选出要删除的
            List<Integer> dbProductSubIdList = dbProductSubList.stream()
                    .map(ProductSub::getProductId).collect(Collectors.toList());

            List<Integer> toDeletedIdList = new ArrayList<>();
            List<Integer> addedIdList = new ArrayList<>();
            for (Integer productId : dbProductSubIdList) {
                if (!productIdList.contains(productId)) {
                    toDeletedIdList.add(productId);

                    delImg(shopId, productId, branchId);
                }else {
                    addedIdList.add(productId);
                }
            }

            if (toDeletedIdList.size() > 0) {
                Condition procutSubCondition = new Condition(ProductSub.class);
                procutSubCondition.or().andIn("productId", toDeletedIdList);
                productSubMapper.deleteByCondition(procutSubCondition);
            }

            if (addedIdList.size() > 0) {
                productIdList.removeAll(addedIdList);
            }
        }*/

        Shop shop = shopService.findShopById(shopId);

        List<Integer> dbProductSubIdList = null;
        if (dbProductSubList != null && dbProductSubList.size() > 0) {
            dbProductSubIdList = dbProductSubList.stream()
                    .map(ProductSub::getProductId).collect(Collectors.toList());
        }else{
            //针对无今日菜品库的商户，初次添加先清空旧菜品库
            if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
                ypRecService.delAllImg(branchId, bowlService.localRecIp);
            }
        }

        List<ProductSub> productSubList = new ArrayList<>();
        for (Integer productId : productIdList) {
            if (dbProductSubIdList!= null && dbProductSubIdList.contains(productId)) {
                continue;
            }
            ProductSub productSub = new ProductSub();
            productSub.setProductId(productId);
            productSub.setShopId(shopId);
            productSub.setBranchId(branchId);
            productSub.setCreateTime(new Date());

            productSubList.add(productSub);

            Condition imgCondition = new Condition(LogProductImgFromUser.class);
            imgCondition.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
                .andEqualTo("baiduDeleted", 0)
            ;



            if(shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
                ThreadManager.executorService.execute(() ->
                    ypRecService.addProductImg(productId, branchId, bowlService.localRecIp)
                );

            }else{
                List<LogProductImgFromUser> logProductImgFromUserList = logProductImgFromUserMapper.selectByCondition(imgCondition);

                if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
                    for (LogProductImgFromUser logProductImgFromUser : logProductImgFromUserList) {
                        addImg(shopId, productId, logProductImgFromUser.getImgCutNetUrl(), branchId);
                    }
                }

                List<LogProductImg> logProductImgList = logProductImgMapper.selectByCondition(imgCondition);

                if (logProductImgList != null && logProductImgList.size() > 0) {
                    for (LogProductImg logProductImg : logProductImgList) {
                        addImg(shopId, productId, logProductImg.getCutImg(), branchId);
                    }
                }
            }

        }
        if (productSubList != null && productSubList.size() > 0) {
            productSubMapper.insertList(productSubList);
        }

    }

    public void addImg(Integer shopId, Integer productId, String imgUrl, Integer branchId){
        //添加新图片
        ThreadManager.executorService.execute(() -> {
            try {

                String filename = null;
                String cutSrcNetUrl = null;
                if (imgUrl.startsWith("http")) {

                    String shopFilepath = bowlService.wxapiFilepath + "/usr/local/nginx/html/images/source/" + shopId;
                    File shopFile = new File(shopFilepath);

                    if (!shopFile.exists()) {
                        shopFile.mkdir();
                    }

                    String filepath = "/usr/local/nginx/html/images/source/" + shopId + "/" + productId;
                    File file = new File(filepath);

                    if (!file.exists()) {
                        file.mkdir();
                    }

                    filename = filepath + "/" + UUID.randomUUID() + ".png";

                    FileDownloader.downloadNet(imgUrl, filename);

                    cutSrcNetUrl = imgUrl.replaceAll("/usr/local/nginx/html/", "http://binguoai.com/");
                }else {
                    filename = imgUrl;

                    cutSrcNetUrl = imgUrl.replaceAll("/opt/img/", "http://binguoai.com/wxproductimg/");
                }



//                String cont_sign = baiduRecUtil.addImgCur(shopId, branchId, filename, shopId + "_" + productId);
                List<Map<String, String>> mapList = baiduRecUtil.addImgCurList(shopId, branchId, filename, shopId + "_" + productId);

                if (mapList != null && mapList.size() > 0) {
                    for (Map<String, String> map : mapList) {
                        String appid = map.get("appid");
                        String contSign = map.get("contSign");

                        LogProductImgFromUser logProductImg = new LogProductImgFromUser();
                        logProductImg.setCutImg(filename);
                        logProductImg.setProductId(productId);
                        logProductImg.setShopId(shopId);
                        logProductImg.setSourceImg(filename);
                        logProductImg.setContSign(contSign);
                        logProductImg.setCreateTime(new Date());
                        logProductImg.setBaiduDeleted(0);
                        logProductImg.setBranchId(branchId);
                        logProductImg.setFromCorrect(1);
                        logProductImg.setSubDb(1);
                        logProductImg.setImgSrcNetUrl(cutSrcNetUrl);
                        logProductImg.setImgCutNetUrl(cutSrcNetUrl);
                        logProductImg.setBaiduAppId(appid);

                        logProductImgFromUserMapper.insert(logProductImg);
                    }
                }



//
//                ProductSub productSub = new ProductSub();
//                productSub.setBranchId(branchId);
//                productSub.setShopId(shopId);
//                productSub.setCreateTime(new Date());
//                productSub.setProductId(productId);
//                productSubMapper.insertSelective(productSub);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void delImg(Integer shopId, Integer productId, Integer branchId){

        //删除图片
        Condition logProductImgCondtion = new Condition(LogProductImgFromUser.class);
        logProductImgCondtion.or().andEqualTo("shopId", shopId)
                .andEqualTo("productId", productId)
                .andEqualTo("baiduDeleted", 0)
                .andEqualTo("subDb", 1)
        ;

        List<LogProductImgFromUser> logProductImgList = logProductImgFromUserMapper.selectByCondition(logProductImgCondtion);
        if (logProductImgList != null && logProductImgList.size() > 0) {
            ThreadManager.executorService.execute(() -> {
                for (LogProductImgFromUser logProductImg : logProductImgList) {
                    String contSign = logProductImg.getContSign();
                    if(!baiduRecUtil.delImgCurList(contSign, shopId, branchId, logProductImg.getBaiduAppId())){
//                    if(!baiduRecUtil.delImgCur(contSign, shopId, branchId)){
                        LogShopBaiduImgDel logShopBaiduImgDel = new LogShopBaiduImgDel();
                        logShopBaiduImgDel.setImgType(2);
                        logShopBaiduImgDel.setStatus(0);
                        logShopBaiduImgDel.setLogId(logProductImg.getId());
                        logShopBaiduImgDelMapper.insertSelective(logShopBaiduImgDel);
                    }else{
                        LogProductImgFromUser temp = new LogProductImgFromUser();
                        temp.setId(logProductImg.getId());
                        temp.setBaiduDeleted(1);
                        logProductImgFromUserMapper.updateByPrimaryKeySelective(temp);
                    }
                }
            });
        }
    }
}
